// subpkg/mallManagement/mallManagement.js
//页面设计思路：商品发布每个用户自己发布的商品列表进行管理，商品出售是用户卖出去的订单信息管理
//调用数据库
const db = wx.cloud.database()
//定义初始化数据
let totalData = 0
Page({
    /**
     * 页面的初始数据
     */
    data: {
        titleList: [{
            title: '商品发布'
        }, {
            title: '商品出售'
        }], //导航标题数组
        currentIndex: 0, //导航当前选择
        goodsList: [], //空数组存放数据库数据
        editId: '', //存放编辑商品的id
        pageSize: 6,
        pageNum: 1,
        total: 0,
        hiddenFlag: true,
        // 商品出售底下功能按钮
        btnText: [[],
            [{bgColor: '#ee7800', text: '待发货'}],
            [{bgColor: '#55D686', text: '待收货'}],
            [{bgColor: '#cd5e3c', text: '待售后'}],
            [{bgColor: '#c0c6c9', text: '已完成'}],
            [{bgColor: '#00a3af', text: '待退款'}],
            [{bgColor: '#c0c6c9', text: '已退款'}]]
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        this.getDataList(1)
    },
    /**
     * 获取数据方法
     */
    getDataList(pageNum) {
        if(this.data.currentIndex === 0) {
            this.getGoodsList(pageNum);
        }else {
            this.getOrderList(pageNum);
        }
    },
    /**
     * 获取发布商品列表
     * @param {*} pageNum 
     */
    getGoodsList(pageNum) {
        wx.showLoading({
            title: '加载中···',
        });
        // 获取数据库idlemallSend数据
        wx.cloud.callFunction({
            name: 'databaseApi',
            data: {
                type: 'getIdlemallOfUser',
                reqData: {
                    pageSize: this.data.pageSize,
                    pageNum: pageNum
                }
            }
        }).then(res => {
            // console.log('getGoodsList success ==>', res);
            if (res.result.resData.data) {
                this.setData({
                    ['goodsList[' + (pageNum - 1) + ']']: res.result.resData.data,
                    hiddenFlag: true,
                    total: res.result.resData.total
                });
            }
        }, err => {
            console.log('getGoodsList error ==>', err);
        }).finally(() => {
            wx.hideLoading();
        });
    },
    /**
     * 获取用户发布商品相关的订单
     * @param {*} pageNum 
     */
    getOrderList(pageNum) {
        wx.showLoading({
          title: '加载中',
        });
        wx.cloud.callFunction({
            name: 'databaseApi',
            data: {
                type: 'getOrderByUser',
                reqData: {
                    pageSize: this.data.pageSize,
                    pageNum: pageNum
                }
            }
        }).then(res => {
            // console.log('get order success ==>', res);
            if (res.result.resData.data) {
                this.setData({
                    ['goodsList[' + (pageNum - 1) + ']']: res.result.resData.data,
                    hiddenFlag: true,
                    total: res.result.resData.total
                });
            }
        }, err => {
            console.log('get order error ==>', err);
        }).finally(() => {
            wx.hideLoading();
        });
    },
    /**
     * 点击查看订单详情
     * @param {*} e 
     */
    onToDetail(e) {
        let id = e.currentTarget.dataset.id;
        wx.navigateTo({
          url: '/pages/order_details/order_details?type=3&id=' + id,
        });
    },
    /**
     * 处理商品出售底部的按钮
     * @param {*} e 
     */
    onToDeal(e) {
        let type = e.currentTarget.dataset.type;
        let pageNum = e.currentTarget.dataset.pagenum;
        let index = e.currentTarget.dataset.index;
        let orderId = this.data.goodsList[pageNum][index].id;
        console.log('btn ==>', type, pageNum, index, orderId);
        switch(type) {
            case '待发货':
                this.deliverGoods(orderId, pageNum, index);
                break;
            case '待收货':
                this.receivingGoods();
                break;
            case '待售后':
                this.handlingAfterSales(orderId);
                break;
            case '已完成':
                this.completeOrder();
                break;
            case '待退款':
                this.refundOrder(orderId, pageNum, index);
                break;
            case '已退款':
                this.refundedOrder();
                break;
        }
    },
    /**
     * 发货
     * @param {*} orderId 
     */
    deliverGoods(orderId, pageNum, index) {
        // 将订单状态改为：2-已发货
        wx.showModal({
            title: '提示',
            content: '您确定要对订单进行发货吗？',
            confirmColor: '#55D686',
            cancelColor: '#F87026'
        }).then(res => {
            // console.log('cancel modal success ==>', res);
            if (res.confirm) {
                // 确认发货
                this.updateOrderStatus(orderId, pageNum, index, 2, '发货成功');
            } else if (res.cancel) {
                this.$showMsg('已取消发货');
            }
        }, err => {
            console.log('cancel modal error ==>', err);
        });
    },
    /**
     * 处理售后
     * @param {*} orderId 
     */
    handlingAfterSales(orderId) {
        wx.showModal({
            title: '提示',
            content: '您是否要联系买家？',
            confirmColor: '#55D686',
            cancelColor: '#F87026'
        }).then(res => {
            // console.log('cancel modal success ==>', res);
            if (res.confirm) {
                // 确认申请
                this.onToContactBuyer(orderId);
            } else if (res.cancel) {
                this.$showMsg('已取消售后');
            }
        }, err => {
            console.log('cancel modal error ==>', err);
        });
    },
    /**
     * 联系买家
     */
    onToContactBuyer(orderId) {
        wx.cloud.callFunction({
            name: 'databaseApi',
            data: {
                type: 'getBuyIdByOrderId',
                reqData: orderId
            }
        }).then(res => {
            // console.log('get buyer userID success ==>', res);
            let userID = res.result.resData;
            const payloadData = {
                conversationID: `C2C${userID}`,
            };
            wx.navigateTo({
                url: `/pages/chat/chat?conversationInfomation=${JSON.stringify(payloadData)}`,
            });
        }, err => {
            console.log('get buyer uerID error ==>', err);
        });
    },
    /**
     * 待收货
     */
    receivingGoods() {
        this.$showMsg('请耐心等待用户确认完成订单');
    },
    /**
     * 已完成订单
     */
    completeOrder() {
        this.$showMsg('订单已完成，无需操作');
    },
    /**
     * 订单退款
     * @param {*} orderId 
     * @param {*} pageNum 
     * @param {*} index 
     * @param {*} status 
     */
    refundOrder(orderId, pageNum, index) {
        // 将订单状态改为：6-已退款
        wx.showModal({
            title: '提示',
            content: '您确定要对订单进行退款吗？',
            confirmColor: '#55D686',
            cancelColor: '#F87026'
        }).then(res => {
            // console.log('cancel modal success ==>', res);
            if (res.confirm) {
                // 确认发货
                this.updateOrderStatus(orderId, pageNum, index, 6, '发货成功');
            } else if (res.cancel) {
                this.$showMsg('已取消退款');
            }
        }, err => {
            console.log('cancel modal error ==>', err);
        });
    },
    /**
     * 订单已退款
     */
    refundedOrder() {
        this.$showMsg('订单已退款');
    },
    /**
     * 修改指定订单的状态
     * @param {*} orderId 
     * @param {*} status 
     */
    updateOrderStatus(orderId, pageNum, index, status, msg = '') {
        let goodsName = this.data.goodsList[pageNum][index].goodsMess.goodsData.goodsName;
        wx.cloud.callFunction({
            name: 'databaseApi',
            data: {
                type: 'updateOrderStatus',
                reqData: {
                    orderId: orderId,
                    status: status
                }
            }
        }).then(res => {
            // console.log('update order status success ==>', res);
            this.addGoodsMess(orderId, goodsName, status);
            this.setData({
                ['goodsList[' + pageNum + '][' + index + '].orderStatus']: status
            });
            if(msg) {
                this.$showMsg(msg, 'success');
            }
        }, err => {
            console.log('update order status error ==>', err);
        });
    },
    /**
     * 添加消息
     * @param {*} orderId 
     * @param {*} goodsName 
     * @param {*} state 
     */
    addGoodsMess(orderId, goodsName, state) {
        // 添加消息
        wx.cloud.callFunction({
            name: 'databaseApi',
            data: {
                type: 'addGoodsMess',
                reqData: {
                    orderId: orderId,
                    goodsName: goodsName,
                    state: state
                }
            }
        });
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {
        if (this.data.pageNum * this.data.pageSize < this.data.total) {
            this.setData({
                pageNum: this.data.pageNum + 1
            });
            this.getDataList(this.data.pageNum);
        } else {
            this.$showMsg('没有更多数据了');
        }

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppgoodsList() {

    },
    /**
     * 切换导航
     */
    onTurnOther: function (e) {
        let current = e.currentTarget.dataset.title
        this.setData({
            goodsList: [],
            pageNum: 1,
            hiddenFlag: false,
            currentIndex: current
        });
        this.getDataList(1);
    },
    /**
     * 商品发布中修改商品状态-出售中和已下架
     */
    onTurnStatus(e) {
        let pageNum = e.currentTarget.dataset.pagenum;
        let index = e.currentTarget.dataset.index;
        let status = e.currentTarget.dataset.status;
        let goodsId = this.data.goodsList[pageNum][index].id;
        if(status === '无库存') {
            this.$showMsg('商品没有库存了，无法改变状态');
        }else {
            wx.showModal({
                title: '提示',
                content: '您确定要改变商品状态吗？',
                confirmColor: '#55D686',
                cancelColor: '#F87026'
            }).then(res => {
                // console.log('cancel modal success ==>', res);
                if (res.confirm) {
                    // 确认申请
                    switch (status) {
                        case '出售中':
                            this.setData({
                                ['goodsList[' + pageNum + '][' + index + '].goodsStatus']: '已下架'
                            });
                            this.updateGoodsStatus(goodsId, '已下架');
                            break;
                        case '已下架':
                            this.setData({
                                ['goodsList[' + pageNum + '][' + index + '].goodsStatus']: '出售中'
                            });
                            this.updateGoodsStatus(goodsId, '出售中');
                            break;
                    }
                } else if (res.cancel) {
                    this.$showMsg('已取消操作');
                }
            }, err => {
                console.log('cancel modal error ==>', err);
            });
        }
    },
    /**
     * 将指定商品状态改为对应的
     * @param {*} goodsId 
     * @param {*} status 
     */
    updateGoodsStatus(goodsId, status) {
        db.collection('idlemallSend').doc(goodsId).update({
            data: {
                goodsStatus: status
            }
        }).then(res => {
            // console.log('update goods status success ==>', res);
        }, err => {
            console.log('update goods status error ==>', err);
        });
    },
    /**
     * 发布商品编辑
     */
    turnEdit(e) {
        //获取点击商品下标
        let editIndex = e.currentTarget.dataset.edit;
        let pageNum = e.currentTarget.dataset.pagenum;
        //查找商品的_id
        let id = this.data.goodsList[pageNum][editIndex].id;
        console.log(this.data.goodsList[pageNum][editIndex]);
        //editId 赋值
        this.setData({
            editId: id
        })
        //跳转到商品编辑页面
        wx.navigateTo({
            url: '../issue/issue?id=' + this.data.editId + '&text=修改',
        });
    },
    /**
     * 显示提示信息
     * @param {*} msg 
     * @param {*} type 
     */
    $showMsg(msg, type = 'none') {
        wx.showToast({
            title: msg,
            icon: type
        });
    }
})